package com.xcc.core.netty.client;


import java.math.BigInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xcc.core.config.PropertiesUtil;
import com.xcc.core.netty.NettyLengthClient;
import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.model.LengthModel;
import com.xcc.core.netty.server.Server3389handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ClientLengthHandler extends SimpleChannelInboundHandler<LengthModel> {

	private static final Log LOG = LogFactory.getLog(ClientLengthHandler.class);
 


	@Override
	public void channelActive(ChannelHandlerContext ctx)
			throws Exception {
		int id=  new BigInteger(ctx.channel().id()
				.asShortText(), 16).intValue();
		LOG.debug("连接服务器客户端"+ id);
		ManagerChannel.getAllServer().put("3389",ctx.channel()); 
	}
	
	//传给客户端id 这里会拿到client2 id
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LengthModel msg)
			throws Exception {
		switch(msg.getType()) {
		case 1:
			handle(ctx,msg);
			break;
		case 2:
			LOG.info("心跳检测");
			break;
		case 3:
			proxyConnect(ctx,msg);
			break;
		}
	

	}

	public void proxyConnect(ChannelHandlerContext ctx, LengthModel msg) {
		String[] proxy=new String(msg.getBs()).split("&");
		NettyLengthClient.startProClient(msg.getId(),proxy[0],Integer.parseInt(proxy[1]));
	}
	
	public void handle(ChannelHandlerContext ctx, LengthModel msg) {
	    LOG.info( msg.getBs() );
		/*if("connect".equals(new String(msg.getBs()))) {
			System.out.println("代理客户端："+msg.getId());
			NettyLengthClient.startProClient(msg.getId());
		}else {*/
			int id=  new BigInteger(ctx.channel().id()
					.asShortText(), 16).intValue();
			  LOG.info("msg:"+msg.getId());
			Channel ch=ManagerChannel.getServerChannel2(msg.getId()+"");
			  LOG.info("接收数据："); 
			for(byte b:msg.getBs()) {
				System.out.print((0xff&b)+" ");
			}
			String length=new String(msg.getBs());
			  LOG.info("接收数据长度"+msg.getLength()+"or"+msg.getBs().length); 
			ByteBuf buf=Unpooled.copiedBuffer(msg.getBs());
			ch.writeAndFlush(buf);    
	//	}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
			super.exceptionCaught(ctx, cause);
			new NettyLengthClient(PropertiesUtil.getValue("server.ip"),
			    PropertiesUtil.getIntValue("server.port")).start();
	}

}
